"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AudioMiniLayout = void 0;

var _taro = _interopRequireDefault(require("@tarojs/taro"));

var _classnames = _interopRequireDefault(require("classnames"));

var _react = _interopRequireWildcard(require("react"));

var _components = require("@tarojs/components");

var _spin = _interopRequireDefault(require("../../../spin"));

var _configContext = require("../../../../extends/configContext");

var _icon = _interopRequireDefault(require("../../../../components/icon"));

var _bgView = _interopRequireDefault(require("./bg-view"));

var _progress = _interopRequireDefault(require("../../../progress"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var createInnerAudioContext = _taro.default.createInnerAudioContext || wx.createInnerAudioContext;

var AudioMiniLayout = /*#__PURE__*/function (_Component) {
  _inherits(AudioMiniLayout, _Component);

  var _super = _createSuper(AudioMiniLayout);

  function AudioMiniLayout(props) {
    var _this;

    _classCallCheck(this, AudioMiniLayout);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "eventListenerPlayImpl", function (target) {
      // 如果派发对象是自己，则无效
      if (target === _assertThisInitialized(_this)) return; // 如果不是单例，不生效

      if (!_this.props.singleton) return;
      var audioCtx = _this.state.audioCtx;

      if (audioCtx && audioCtx.pause) {
        audioCtx.pause();

        _this.setState({
          audioCtx: audioCtx
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "playOrStopAudio", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var curIcon, isPlayable, audioCtx;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _this.props.emitter.emit('play', _assertThisInitialized(_this)); // 增加播放前回调


              curIcon = _this.state.audioImg;

              _this.setAudioImg('iconLoading');

              _context.next = 5;
              return _this.props.beforePlay();

            case 5:
              isPlayable = _context.sent;

              if (!(isPlayable === false)) {
                _context.next = 9;
                break;
              }

              _this.setAudioImg(curIcon);

              return _context.abrupt("return");

            case 9:
              audioCtx = _this.state.audioCtx;

              if (audioCtx.paused && !_this.props.disabled) {
                audioCtx.play();
              } else {
                audioCtx.pause();
              }

            case 11:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    })));

    _defineProperty(_assertThisInitialized(_this), "audioTime", function () {
      var _this$state = _this.state,
          audioImg = _this$state.audioImg,
          _this$state$duration = _this$state.duration,
          duration = _this$state$duration === void 0 ? 0 : _this$state$duration;

      if (audioImg === 'iconLoading') {
        return '加载中';
      }

      if (audioImg === 'CloseOutlined') {
        return '加载失败';
      }

      if (duration === 0 || duration === Infinity) {
        return '未知长度';
      }

      if (duration > 60) {
        return "\u7EA6".concat(Math.floor(duration / 60), "\u5206\u949F");
      }

      return "\u7EA6".concat(duration, "\u79D2");
    });

    _defineProperty(_assertThisInitialized(_this), "renderAudioIcon", function () {
      var clsPrefix = _this.context.clsPrefix;
      var disabled = _this.props.disabled;
      var audioImg = _this.state.audioImg; // 按钮样式

      var iconClassName = (0, _classnames.default)("".concat(clsPrefix, "-audio__wrapper-inner-btn--mini"), {
        'is-disabled': disabled || audioImg === 'CloseOutlined'
      });

      if (disabled) {
        return /*#__PURE__*/_react.default.createElement(_icon.default, {
          name: 'CloseOutlined',
          className: iconClassName
        });
      }

      if (audioImg === 'iconLoading') {
        return /*#__PURE__*/_react.default.createElement(_spin.default, {
          className: iconClassName,
          type: "spinner"
        });
      }

      return /*#__PURE__*/_react.default.createElement(_icon.default, {
        onClick: _this.playOrStopAudio,
        name: audioImg,
        className: iconClassName
      });
    });

    _defineProperty(_assertThisInitialized(_this), "renderContent", function () {
      var clsPrefix = _this.context.clsPrefix;
      var _this$state2 = _this.state,
          currentTime = _this$state2.currentTime,
          duration = _this$state2.duration;
      var percent = currentTime * 100 / duration || 0;
      return /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsPrefix, "-audio__wrapper ").concat(clsPrefix, "-audio__wrapper--mini")
      }, /*#__PURE__*/_react.default.createElement(_progress.default, {
        type: "circle",
        percent: percent,
        lineWidth: 2,
        isShowText: false
      }), /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsPrefix, "-audio__wrapper-inner")
      }, _this.renderAudioIcon()));
    });

    _defineProperty(_assertThisInitialized(_this), "renderText", function () {
      var clsPrefix = _this.context.clsPrefix;
      var onDelete = _this.props.onDelete;
      return /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsPrefix, "-audio__right")
      }, /*#__PURE__*/_react.default.createElement(_components.Text, {
        className: "".concat(clsPrefix, "-audio__tip")
      }, _this.audioTime()), onDelete && /*#__PURE__*/_react.default.createElement(_icon.default, {
        name: "DeleteOutlined",
        className: "".concat(clsPrefix, "-audio__delete"),
        onClick: function onClick() {
          onDelete();
        }
      }));
    });

    _this.state = {
      audioCtx: createInnerAudioContext(),
      audioImg: 'iconLoading',
      currentTime: 0,
      duration: 0,
      childrenRef: null,
      canPlay: false // 音乐链接初始化，保存到onCanPlay

    };
    return _this;
  }

  _createClass(AudioMiniLayout, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      var _this$state3 = this.state,
          audioCtx = _this$state3.audioCtx,
          audioImg = _this$state3.audioImg;
      audioCtx.src = this.props.src;
      audioCtx.loop = !!this.props.loop; // 当播放的时候通过TimeUpdate的回调去更改当前播放时长和总时长（总时长更新放到onCanplay回调中会出错）

      audioCtx.onTimeUpdate(function () {
        if (audioCtx.currentTime > 0 && audioCtx.currentTime <= 1) {
          _this2.setState({
            currentTime: 0
          });
        } else if (audioCtx.currentTime !== Math.floor(audioCtx.currentTime)) {
          _this2.setState({
            currentTime: Math.floor(audioCtx.currentTime)
          });
        }

        var tempDuration = Math.floor(audioCtx.duration);

        if (_this2.state.duration !== tempDuration) {
          _this2.setState({
            duration: tempDuration
          });
        }
      }); // 当音频可以播放就将状态从loading变为可播放

      audioCtx.onCanplay(function () {
        if (audioImg === 'iconLoading') {
          !_this2.state.canPlay && _this2.setAudioImg('PlayOutlined'); // 优先定义audioCtx.duration，以便在点击播放前获取时长
          // eslint-disable-next-line @typescript-eslint/no-unused-expressions

          audioCtx.duration; // 获取音频时长

          setTimeout(function () {
            var tempDuration = Math.floor(audioCtx.duration);

            if (_this2.state.duration !== tempDuration) {
              _this2.setState({
                duration: tempDuration
              });
            }
          }, 10);
        }

        _this2.setState({
          canPlay: true
        });
      }); // 当音频在缓冲时改变状态为加载中

      audioCtx.onWaiting(function () {
        if (audioImg !== 'iconLoading') {
          _this2.setAudioImg('iconLoading');
        }
      }); // 开始播放后更改图标状态为播放中

      audioCtx.onPlay(function () {
        _this2.setAudioImg('PauseOutlined');

        _this2.props.onPlay();
      }); // 暂停后更改图标状态为暂停

      audioCtx.onPause(function () {
        _this2.setAudioImg('PlayOutlined');

        var _this2$props$onPause = _this2.props.onPause,
            onPause = _this2$props$onPause === void 0 ? function () {} : _this2$props$onPause;
        onPause();
      }); // 播放结束后更改图标状态

      audioCtx.onEnded(function () {
        if (audioImg !== 'iconPaused') {
          _this2.setAudioImg('PlayOutlined');
        }

        _this2.setState({
          currentTime: 0
        });

        var _this2$props$onEnded = _this2.props.onEnded,
            onEnded = _this2$props$onEnded === void 0 ? function () {} : _this2$props$onEnded;
        onEnded();
      }); // 音频加载失败时 抛出异常

      audioCtx.onError(function (e) {
        if (audioImg !== 'CloseOutlined') {
          _this2.setAudioImg('CloseOutlined');
        }

        var _this2$props$onError = _this2.props.onError,
            onError = _this2$props$onError === void 0 ? function () {} : _this2$props$onError;
        onError(); // throw new Error(e.errMsg);
      });
      this.props.emitter.on('play', this.eventListenerPlayImpl);
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var newSrc = nextProps.src || '';

      if (this.props.src !== newSrc && newSrc !== '') {
        var audioCtx = this.state.audioCtx;

        if (!audioCtx.paused) {
          // 如果还在播放中，先进行停止播放操作
          audioCtx.stop();
        }

        audioCtx.src = nextProps.src; // 重置当前播放时间和总时长

        this.setState({
          currentTime: 0,
          duration: 0
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.props.emitter.removeListener('play', this.eventListenerPlayImpl);
      this.state.audioCtx.stop();
      this.state.audioCtx.destroy();
    } // 设置按钮icon

  }, {
    key: "setAudioImg",
    value: function setAudioImg(newImg) {
      this.setState({
        audioImg: newImg
      });
    } // 播放&暂停

  }, {
    key: "render",
    value: function render() {
      var clsPrefix = this.context.clsPrefix;
      var audioImg = this.state.audioImg;
      return /*#__PURE__*/_react.default.createElement(_components.View, {
        className: (0, _classnames.default)("".concat(clsPrefix, "-audio"))
      }, /*#__PURE__*/_react.default.createElement(_bgView.default, {
        leftChildren: this.renderContent(),
        rightChildren: this.renderText(),
        isPlay: audioImg === 'PauseOutlined'
      }));
    }
  }]);

  return AudioMiniLayout;
}(_react.Component);

exports.AudioMiniLayout = AudioMiniLayout;

_defineProperty(AudioMiniLayout, "contextType", _configContext.ConfigContext);